# application/mapper/system/dict.py
import datetime
from application.extensions.databases import db
from application.models.detection.product import Product
from typing import List, Dict, Any
from sqlalchemy.orm import joinedload
from application.models.detection.product_model import ProductModel


class ProductMapper:
    """字典数据访问层"""

    @staticmethod
    def get_product_list(
        page_num: int, page_size: int, conditions: Dict[str, Any] = None
    ) -> tuple:
        """
        分页获取产品型号数据列表
        :param page_num: 页码
        :param page_size: 每页数量
        :param conditions: 查询条件
        :return: (产品型号数据列表, 总数)
        """
        query = db.session.query(Product)

        # 添加查询条件
        if conditions:
            if conditions.get("productModelId"):
                query = query.filter(
                    Product.product_model_id == conditions["productModelId"]
                )
            if conditions.get("productName"):
                query = query.filter(
                    Product.product_name.like(f"%{conditions['productName']}%")
                )
            if conditions.get("productNo"):
                query = query.filter(
                    Product.product_no.like(f"%{conditions['productNo']}%")
                )
            if conditions.get("contractNo"):
                query = query.filter(
                    Product.contract_name.like(f"%{conditions['contractNo']}%")
                )

        # 获取总数
        total = query.count()

        # 分页查询
        offset = (page_num - 1) * page_size
        product_list = (
            query.order_by(Product.product_id).offset(offset).limit(page_size).all()
        )

        return product_list, total

    @staticmethod
    def create_product(product: Product) -> Product:
        """
        创建产品型号
        :param product: 产品型号对象
        :return: 创建后的产品型号对象
        """
        db.session.add(product)
        db.session.commit()
        return product

    @staticmethod
    def update_product(product: Product) -> Product:
        """
        更新产品型号
        :param product: 产品型号对象
        :return: 更新后的产品型号对象
        """
        db.session.commit()
        return product

    @staticmethod
    def get_all_products() -> List[Dict]:
        """
        获取所有产品数据及产品型号字段
        :return: 产品数据列表（包含产品型号）
        """

        results = (
            db.session.query(
                Product.product_id,
                Product.product_model_id,
                Product.product_name,
                Product.product_no,
                Product.contract_name,
                Product.create_dept,
                Product.create_by,
                Product.create_time,
                Product.update_by,
                Product.update_time,
                Product.del_flag,
                Product.remark,
                ProductModel.product_model,
                ProductModel.product_type,
            )
            .join(
                ProductModel, Product.product_model_id == ProductModel.product_model_id
            )
            .filter(Product.del_flag == "0", ProductModel.del_flag == "0")
            .all()
        )
        return results


    @staticmethod
    def get_product_by_id(product_id: int) -> Product:
        """
        根据ID获取产品型号
        :param product_id: 产品型号ID
        :return: 产品型号对象
        """
        return (
            db.session.query(Product).filter(Product.product_id == product_id).first()
        )

    @staticmethod
    def delete_product(product: Product) -> None:
        """
        删除产品型号
        :param product: 产品型号对象
        :return: None
        """
        # 设置删除标志为1，表示已删除
        product.del_flag = 1
        # 更新删除时间
        db.session.commit()
